package q662_widthOfBinaryTree;

import CommonClass.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class Solution_1 {
    /*
    用两个队列来实现求最大宽度的方式
     */
    public int widthOfBinaryTree(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        LinkedList<Integer> queueIdx = new LinkedList<>();
        queue.offer(root);
        queueIdx.offer(1);
        int res = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                int idx = queueIdx.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                    queueIdx.offer(idx * 2);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                    queueIdx.offer(idx * 2 + 1);
                }
            }
            if (!queueIdx.isEmpty()) res = Math.max(res, queueIdx.getLast() - queueIdx.getFirst());
        }

        return res;
    }
}
